<?php

namespace App\Services\MakeBoxProductOrder;

use App\Models\Order;
use App\Models\Address;
use App\Models\Coupon;
use App\Models\BlindBoxOrder;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class RefreshBoxProductOrderRequest extends FormRequest
{
	protected ?Address $address = null;

	public function rules(): array
	{

		$orderId =  (int)request('blind_box_order_id');
		if ($orderId) {
			$this->order = BlindBoxOrder::find($orderId);
		}
		
		return [
			'blind_box_order_id' => ['required', $this->blindBoxOrder()],
		];
	}

	

	public function blindBoxOrder()
	{

		return function ($attribute, $value, $fail) {
			if (!$box = BlindBoxOrder::find($value)) {
				return $fail('订单不存在');
			}elseif($box->is_taken){
				return $fail('订单已经确认');
			}elseif($box->is_refresh){
				return $fail('每个盲盒最多能重抽一次');
			}

			$refreshCoupon = Coupon::where('coupon_category','refresh')->first();
			if (!$refreshCoupon->id) {
				return $fail('重抽卡不存在');
			}
			$coupon = $this->user()->coupons->where('coupon_id',$refreshCoupon->id)->where('is_used',false)->first();
			if(!isset($coupon->id)){
				return $fail('没有重抽卡');
			}
			return true;
		};
	}

	

	public function getBlindBoxOrder()
	{
		return $this->order;
	}

	
}
